package com.backend.system.common;

import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;
import java.util.Set;

import static org.springframework.http.HttpStatus.OK;

/**
 * 全局异常处理
 *
 * @author backend-manage
 */
@Slf4j
@RestControllerAdvice
public class ExceptionInterceptor {

    /**
     * sa-toke权限校验
     */
    @ExceptionHandler(NotPermissionException.class)
    @ResponseStatus(OK)
    ResponseEntity<String> handleNotPermissionException(NotPermissionException exception) {
        log.warn("NotPermissionException occurred ! ", exception);
        return new ResponseEntity<>("权限不足", "403", null);
    }

    /**
     * sa-toke角色校验
     */
    @ExceptionHandler(NotRoleException.class)
    @ResponseStatus(OK)
    ResponseEntity<String> handleNotRoleException(NotRoleException exception) {
        log.warn("NotRoleException occurred ! ", exception);
        return new ResponseEntity<>("当前用户角色错误", "403", null);
    }


    /**
     * 违反约束，javax扩展定义与自定义校验
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(OK)
    ResponseEntity<String> handleConstraintViolationException(ConstraintViolationException exception) {
        log.warn("handleConstraintViolationException occurred ! ", exception);
        Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        StringBuilder sBuffer = new StringBuilder();
        while (iterator.hasNext()) {
            sBuffer.append(" ").append(iterator.next().getMessage()).append(";");
        }
        return new ResponseEntity<>(sBuffer.toString(), "500", null);
    }

    /**
     * 参数无效，如JSON请求参数违反约束
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(OK)
    ResponseEntity<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        log.warn("handleMethodArgumentNotValidException occurred ! ", exception);
        StringBuilder stringBuffer = new StringBuilder();
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            stringBuffer.append(error.getDefaultMessage()).append(";");
        }
        return new ResponseEntity<>(stringBuffer.toString(), "500", null);
    }

    /**
     * 自定义异常处理
     *
     * @param customException 未处理异常
     * @return ResponseEntity
     */
    @ExceptionHandler(CustomException.class)
    @ResponseStatus(OK)
    public ResponseEntity<String> handleCommonException(CustomException customException) {
        log.error("自定义异常", customException);
        return new ResponseEntity<>(customException.getMessage(), customException.getCode(), null);
    }

    /**
     * 其他异常处理
     *
     * @param exception 未处理异常
     * @return ResponseEntity
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(OK)
    public ResponseEntity<String> handleRuntimeException(RuntimeException exception) {
        log.error("系统内部异常", exception);
        return new ResponseEntity<>("系统内部异常", "500", null);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(OK)
    ResponseEntity<String> handleRootException(Exception exception) {
        log.error("未知异常", exception);
        return new ResponseEntity<>(exception.getMessage(), "500", null);
    }
}


